<template>
  <div class="common-layout">
    <el-container id="container">
      <el-header>
        <div id="logo">
          <el-image style="width: 75%;height: 75%;display: flex;margin: 0;padding: 0"
                    :src="imgPrefix+'squareLogo.jpg'" fit="scale-down"/>
          <p style="font-size: 15px;color: aliceblue">金粽子国际影城</p>
        </div>
        <div id="searchAndHeader">
          <div id="searchMovie">
            <el-input
                v-model="mName"
                style="width: 240px"
                placeholder="请输入电影名称"
                :prefix-icon="Search"
                :size="'default'"
                @keyup.enter="handleSearch"
            />
          </div>
          <div id="userHeader">
            <el-dropdown trigger="hover" size="large" type="primary">
              <el-avatar id="header" :size="60" :src="headerUrl" @error="errorHandler"
                         style="display: flex;margin: auto" fit="cover">
              </el-avatar>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>
                    <el-text id="displayName" style="font-size: 20px;margin: 0 auto;">{{
                        displayName
                      }}
                    </el-text>
                    <!--                  <el-badge class="mark"/>-->
                  </el-dropdown-item>
                  <el-dropdown-item divided @click="changeUserInfo">修改个人信息</el-dropdown-item>
                  <el-dropdown-item @click="userOrders">查看订单</el-dropdown-item>
                  <el-dropdown-item @click="userComments">查看评论</el-dropdown-item>
                  <el-dropdown-item @click="toBack" :disabled="isAdmin()">查看后台</el-dropdown-item>
                  <el-dropdown-item divided @click="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </el-header>
      <el-main>
        <div id="typeAndYearFilter">
          <div id="movieType">
            <span style="color: #a4a3a0;margin-right: 20px">类型</span>
            <el-radio-group v-model="typeRadio" size="middle" @change="changeType">
              <el-radio-button border value="">
                全部
              </el-radio-button>
              <el-radio-button border :value="movieType.mtId" v-for="movieType in movieTypes">
                {{ movieType.mtName }}
              </el-radio-button>
            </el-radio-group>
          </div>
          <div id="movieYear">
            <span style="color: #a2a0a4;margin-right: 20px">年代</span>
            <el-radio-group v-model="yearRadio" size="middle" @change="changeYear">
              <el-radio-button border value="">
                全部
              </el-radio-button>
              <el-radio-button border :value="movieYear" v-for="movieYear in movieYears">
                {{ movieYear }}
              </el-radio-button>
            </el-radio-group>
          </div>
        </div>
        <div id="sortRadio">
          <el-radio-group v-model="condition" size="middle" @change="changeCondition">
            <el-radio-button value="0">按热门排序</el-radio-button>
            <el-radio-button value="1">按票房排序</el-radio-button>
            <el-radio-button value="2">按评分排序</el-radio-button>
          </el-radio-group>
        </div>
        <div id="movieList">
          <div id="movieCards">
            <el-card style="max-width: 300px"
                     shadow="always"
                     v-for="movie in currentPageData"
                     :data-mid="movie.mid"
                     @click="showMovieDetail">
              <template #header><b>{{ movie.mName }}</b></template>
              <el-image
                  :src="imgPrefix+movie.mPic" fit="contain"
              />
              <template #footer>
                <el-rate
                    v-model="movie.avgMovieScore"
                    disabled
                    show-score
                    text-color="#ff9900"
                    score-template="{value} 分"/>
              </template>
            </el-card>
          </div>
        </div>

      </el-main>
      <el-footer>
        <div id="page">
          <el-pagination
              v-model:page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              :current-page="currentPage"
              :disabled="false"
              :total="totalCount"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
              background layout="total, sizes, prev, pager, next, jumper"/>
        </div>
      </el-footer>
    </el-container>
  </div>
</template>
<script setup>
import {ElNotification} from "element-plus";
import request from "@/request.js";
import {ref, reactive, inject} from "vue";
import {Search} from "@element-plus/icons-vue";
import SessionStorage from "@/SessionStorage.js";
import {useRouter} from "vue-router";

const router = useRouter();
const loginUser = SessionStorage.getItem("loginUser");
console.log(loginUser.uRole + "+" + loginUser.username);
const isAdmin = () => {
  return loginUser.uRole !== "0" || loginUser.username !== "admin";
}
const mName = ref("");
// 卡片mid
let cardMidGlobal = -1;

// 渲染头像
const displayName = loginUser.displayName;
const uPic = loginUser.uPic;
const imgPrefix = inject('imgPrefix');
const headerUrl = imgPrefix + uPic;
// 输入框查询电影
const movieQueryMNameDto = reactive({
  mName: "",
  pageNo: 1,
  pageSize: 10
})
const handleSearch = () => {
  console.log(mName.value);
  movieQueryMNameDto.mName = mName.value;
  if (mName.value.trim() !== '') {
    request({
      url: "/movie/searchByMName",
      method: "post",
      data: movieQueryMNameDto
    }).then(res => {
      if ('200' === res.code && res.data.list != null) {
        console.log('根据电影名称查询电影成功！');
        console.log('接口返回的数据详情：', res.data);
        // 清空当前页
        currentPageData.splice(0, currentPageData.length);
        // 更新总数据量
        totalCount.value = res.data.totalCount;
        pageSize.value = res.data.pageSize;
        // 更新当前页数据
        currentPageData.push(...res.data.list);
        console.log(currentPageData);
      } else {
        console.log('根据电影名称查询电影失败！');
        ElNotification({
          type: 'error',
          message: res.msg
        })
      }
    })
  } else {
    ElNotification({
      type: 'error',
      message: "您输入的电影名称为空, 即将刷新页面！"
    })
    window.location.reload();
  }
}

// 渲染电影类型列表
// '爱情', '喜剧', '动画', '剧情', '惊悚', '科幻', '动作', '悬疑', '犯罪', '冒险', '运动', '家庭', '古装', '其他'
const movieTypes = reactive([])
request({
  url: "/movieType/selectAll",
  method: "post"
}).then(res => {
  if ('200' === res.code && res.data != null) {
    console.log('查询全部电影类型成功！');
    let mtList = res.data;
    mtList.forEach(item => {
      movieTypes.push(item);
    })
  } else {
    console.log('查询全部电影类型失败！');
    ElNotification({
      type: 'error',
      message: res.msg
    })
  }
})
// 渲染电影年代单选列表
const localYear = new Date().getFullYear();
const movieYears = reactive([localYear - 6, localYear - 5, localYear - 4, localYear - 3, localYear - 2, localYear - 1, localYear])
const typeRadio = ref("");
const changeType = (val) => {
  console.log('电影类型的单选值发生了改变，当前选中的值为：', val);
  typeRadio.value = val;
  // 重新构建movieQuery和movieQueryDto
  movieQuery.mtId = typeRadio.value;
  movieQuery.movieYear = yearRadio.value;
  movieQuery.pageNo = currentPage.value;
  movieQuery.pageSize = pageSize.value;
  movieQuery.movieYear = yearRadio.value;
  movieQueryDto.movieQuery = movieQuery;
  movieQueryDto.condition = condition.value;
  searchMovie();
}
const yearRadio = ref('');
const changeYear = (val) => {
  console.log('电影年代的单选值发生了改变，当前选中的值为：', val);
  yearRadio.value = val;
  // 重新构建movieQuery和movieQueryDto
  movieQuery.mtId = typeRadio.value;
  movieQuery.movieYear = yearRadio.value;
  movieQuery.pageNo = currentPage.value;
  movieQuery.pageSize = pageSize.value;
  movieQuery.movieYear = yearRadio.value;
  movieQueryDto.movieQuery = movieQuery;
  movieQueryDto.condition = condition.value;
  searchMovie();
}
// 渲染热门，票房，评分单选按钮
const condition = ref('0')
const changeCondition = (val) => {
  console.log('电影排序的单选值发生了改变，当前选中的值为：', val);
  condition.value = val;
  // 重新构建movieQuery和movieQueryDto
  movieQuery.mtId = typeRadio.value;
  movieQuery.movieYear = yearRadio.value;
  movieQuery.pageNo = currentPage.value;
  movieQuery.pageSize = pageSize.value;
  movieQuery.movieYear = yearRadio.value;
  movieQueryDto.movieQuery = movieQuery;
  movieQueryDto.condition = condition.value;
  searchMovie();
}
// 电影列表
// 电影列表分页
const currentPage = ref(1);
const pageSize = ref(10);
const totalCount = ref(0);
// 用于存储当前页的数据
const currentPageData = reactive([]);


const movieQuery = reactive({
  mtId: typeRadio.value,
  movieYear: yearRadio.value,
  pageNo: currentPage.value,
  pageSize: pageSize.value
})
const movieQueryDto = reactive({
  movieQuery: movieQuery,
  condition: condition.value
});

const searchMovie = () => request({
  url: "/movie/searchMovie",
  method: "post",
  data: movieQueryDto
}).then(res => {
  if ('200' === res.code && res.data != null) {
    console.log('查询全部电影成功！');
    console.log('接口返回的数据详情：', res.data);
    if (res.data.page && Array.isArray(res.data.page.list) && typeof res.data.page.totalCount === 'number') {
      // 清空原有数据
      currentPageData.splice(0, currentPageData.length);
      // 更新总数据量
      totalCount.value = res.data.page.totalCount;
      // 更新当前页数据
      const queryList = res.data.page.list;
      queryList.forEach((item) => {
        currentPageData.push(item);
      });
    } else {
      console.log('返回格式参数错误！');
      ElNotification({
        type: 'error',
        message: "返回格式参数错误！"
      })
    }
  } else {
    console.log('查询全部电影失败！');
    ElNotification({
      type: 'error',
      message: res.msg
    })
  }
})
searchMovie();
// 处理当前页码改变的方法
const handleCurrentChange = async (newPage) => {
  console.log("pageNo修改为第" + newPage + "页！");
  currentPage.value = newPage;
  if (mName.value.trim() !== '') {
    movieQueryMNameDto.mName = mName.value;
    movieQueryMNameDto.pageNo = currentPage.value;
    movieQueryMNameDto.pageSize = pageSize.value;
    await handleSearch();
  } else {
    // 重新构建movieQuery和movieQueryDto
    movieQuery.mtId = typeRadio.value;
    movieQuery.movieYear = yearRadio.value;
    movieQuery.pageNo = currentPage.value;
    movieQuery.pageSize = pageSize.value;
    movieQuery.movieYear = yearRadio.value;
    movieQueryDto.movieQuery = movieQuery;
    movieQueryDto.condition = condition.value;
    await searchMovie();
  }
};

// 处理每页显示数量改变的方法
const handleSizeChange = (newSize) => {
  console.log("pageSize修改为每页" + newSize + "条！");
  pageSize.value = newSize;
  currentPage.value = 1;
  if (mName.value.trim() !== '') {
    movieQueryMNameDto.mName = mName.value;
    movieQueryMNameDto.pageNo = currentPage.value;
    movieQueryMNameDto.pageSize = pageSize.value;
    handleSearch();
  } else {
    // 重新构建movieQuery和movieQueryDto
    movieQuery.mtId = typeRadio.value;
    movieQuery.movieYear = yearRadio.value;
    movieQuery.pageNo = currentPage.value;
    movieQuery.pageSize = pageSize.value;
    movieQuery.movieYear = yearRadio.value;
    movieQueryDto.movieQuery = movieQuery;
    movieQueryDto.condition = condition.value;
    searchMovie();
  }
};

const showMovieDetail = (event) => {
  const cardMid = event.currentTarget.dataset.mid;
  cardMidGlobal = cardMid;
  router.push({name: "MovieDetail", params: {mid: cardMid}});
  console.log("查看电影详情的id：" + cardMid);

}

// 用户头像是否显示异常
const errorHandler = () => false


const uidLocal = loginUser.uid;
const changeUserInfo = () => {
  router.push("/userInfo");
  console.log("查看用户信息的uid：" + uidLocal);
}
const userOrders = () => {
  router.push("/userOrders");
  console.log("查看用户订单的uid：" + uidLocal);
}
const userComments = () => {
  router.push("/userComments");
  console.log("查看用户评论的uid：" + uidLocal);
}

const toBack = () => {
  router.push("/back/frontPage");
}

const logout = () => {
  SessionStorage.removeItem("loginUser");
  ElNotification({
    type: 'success',
    message: '退出登录成功！'
  })
  router.push("/login");
}
</script>

<style scoped>
.common-layout {
  height: 100%;
}

#container {
  height: 100%;
}

.el-header {
  height: 10%;
  background-image: linear-gradient(60deg, #3d3393 0%, #2b76b9 37%, #2cacd1 65%, #35eb93 100%);
  display: flex;
}

#logo p {
  display: inline;
  width: 120px;
  height: 15px;
  position: absolute;
  left: 0;
  margin: 0 auto;
}

#searchAndHeader {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

#searchMovie {
  margin: auto 100px;
}

#userHeader {
  display: flex;
  flex-direction: row-reverse;
}

.el-main {
  height: 70%;
}

#typeAndYearFilter {
  margin-left: 70px;
}

#movieType {
  display: flex;
  margin: 10px 10px;
}

#movieYear {
  display: flex;
  margin: 10px 10px;
}

#sortRadio {
  display: flex;
  margin-left: 90px;
  margin-top: 20px;
}

#movieCards {
  margin-top: 50px;
  margin-left: 50px;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start;
  align-content: space-around;
}

#movieCards .el-card {
  margin: 20px 30px;
}

.el-pagination {
  float: right;
}

.el-row {
  margin-top: 10px;
}
</style>
